package com.example.xmlparsedemo

import android.content.Context
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import javax.xml.parsers.DocumentBuilderFactory

class DomHelper {
    companion object {
        fun getList(context: Context): MutableList<WxAccountBean>? {
            var list: MutableList<WxAccountBean>? = arrayListOf()
            //获取Dom解析工厂类
            var documentBuilderFactory = DocumentBuilderFactory.newInstance()
            //获取解析器
            var documentBuilder = documentBuilderFactory.newDocumentBuilder()
            //获取树模型
            var document = documentBuilder.parse(context.assets.open("demo.xml"))
            //根据标签名获取节点列表
            var elementsByTagName: NodeList = document.getElementsByTagName("WxAccount")
            for (i in 0..elementsByTagName.length-1) {
                var item: Element = (elementsByTagName.item(i)) as Element
                var wxAccountBean = WxAccountBean()
                //获取子节点集合
                var childNodes = item.childNodes
                for (j in 0..childNodes.length-1) {
                    var childNode = childNodes.item(j)
                    //是否是元素节点
                    if (childNode.nodeType == Node.ELEMENT_NODE) {
                        var childElement = childNode as Element
                        when (childElement.nodeName) {
                            "name" -> {
                                wxAccountBean.name = childElement.firstChild.nodeValue
                            }
                            "sex" -> {
                                wxAccountBean.sex = childElement.firstChild.nodeValue
                            }
                        }
                    }
                }
                list?.add(wxAccountBean)
            }
            return list
        }
    }
}